<template>
  <section>
    <div :class="signUpActive === true ? 'container active' : 'container'">
      <div class="user sign-in-box">
        <div class="img-box"><img src="../assets/sign/in.jpg" alt="" /></div>
        <div v-loading="signInLoading" class="form-box" @keyup.enter="login">
          <el-form ref="signInForm" :model="signIn" :rules="signInRules" class="form">
            <!-- 登录页面 -->
            <h2>登录</h2>
            <el-form-item prop="username">
              <el-input
                v-model.trim="signIn.username"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model.trim="signIn.password"
                type="password"
                placeholder="密码"
              ></el-input>
            </el-form-item>
            <div
              class="tips"
              style="float:right;">
              <el-link
                type="white"
                @click="retrievePWD">忘记密码</el-link>
            </div>
            <el-button type="primary" class="submit-btn" @click="login">
              登录
            </el-button>
            <p class="signup">
              还没有账号吗？
              <span @click="toggle">点击注册</span>
            </p>
          </el-form>
        </div>
      </div>
      <!-- 注册页面 -->
      <div class="user sign-up-box">
        <div v-loading="signUpLoading" class="form-box">
          <el-form
            ref="signUpForm"
            :model="signUp"
            :rules="signUpRules"
            class="form"
          >
            <h2>创建你的账号</h2>
            <el-form-item prop="username">
              <el-input
                v-model="signUp.username"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="signUp.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="signUp.password"
                placeholder="密码"
                autocomplete="new-passoword"
                @focus="changeType"
              ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="signUp.confirmPassword"
                placeholder="确认密码"
                @focus="changeType"
              ></el-input>
            </el-form-item>
            <!-- 身份选择：老师or学生 -->
            <el-form-item prop="identity">
              <el-select
                v-model="signUp.identity"
                class="full-width"
                placeholder="请选择身份"
              >
                <el-option
                  v-for="item in identities" :key="item.value"
                  :label="item.label" :value="item.value" @click.native="getIdentity"></el-option>
              </el-select>
            </el-form-item>
            <!-- 三级联动省市区选择 -->
            <div class="ShengShiQu">
              <el-select v-model="form.province" clearable placeholder="省" @change="seletekey($event, 'province')">
                <el-option v-for="(val, key) in provinces" :key="key" :label="val" :value="val" />
              </el-select>
              <el-select v-model="form.city" clearable placeholder="市" @change="seletekey($event, 'city')">
                <el-option v-for="(val, key) in citys" :key="key" :label="val" :value="val" />
              </el-select>
              <el-select v-model="form.area" clearable placeholder="区" @change="seletekey($event, 'area')">
                <el-option v-for="(val,key) in areas" :key="key" :label="val" :value="val" />
              </el-select>
            </div>
            <el-form-item prop="school">
              <el-select v-model="value" filterable placeholder="请选择学校" class="full-width" @click.native="getSchoolInfo()">
                <el-option
                  v-for="item in schoolInfo"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                  @click.native="getChoosedSchoolName(item)"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="grade">
              <el-select
                v-model="signUp.grade"
                class="full-width"
                placeholder="请选择年级"
              >
                <el-option-group
                  v-for="period in grades"
                  :key="period.label"
                  :label="period.label"
                >
                  <el-option
                    v-for="grade in period.grades"
                    :key="period.label + grade"
                    :label="period.label + numberZh[grade] + '年级'"
                    :value="[period.code, grade]"
                  ></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            <!-- 学科选择 -->
            <el-form-item prop="subject" v-if="showsubject">
              <el-select v-model="signUp.subject" 
                class="full-width" 
                placeholder="请选择学科" 
                @click.native="getSubject">
                <el-option
                  v-for="item in subjects"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-button
              type="primary"
              class="submit-btn"
              @click="validateSignUp"
            >
              注册
            </el-button>
            <p class="signup">
              已有账号吗？
              <span @click="toggle">点击登录</span>
            </p>
          </el-form>
        </div>
        <div class="img-box"><img src="../assets/sign/up.jpg" alt="" /></div>
      </div>
    </div>
  </section>
</template>

<script>
// import { register, login, authentication } from '@/api/auth'
import { register, login } from '@/api/auth'
// 导入需要的地区数据
import { pcaa } from 'area-data'
import { getSchoollist } from '@/api/user'
import { getCatalogSubject } from '@/api/catalog'
export default {
  name: 'Sign',
  data() {
    // 确认密码的validator
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!/^(?=.*[a-zA-Z])(?=.*\d)[^]{8,18}$/.test(value)) {
        callback(new Error('密码需要8-18位，且需要包含数字和字母'))
      } else {
        if (this.signUp.confirmPassword !== '') {
          this.$refs.signUpForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.signUp.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      signUpActive: false,
      signInLoading: false,
      signUpLoading: false,

      // 新增区域数据
      form: {},
      pcaaData: pcaa,
      // 区域数据
      provinces: pcaa['86'],
      citys: [],
      areas: [],
      areaCodeQu: '',
      // 新增区域数据结束

      // 新增学校数据搜素
      value: '',
      schoolInfo: [],
      // 新增学校数据搜素结束

      signIn: {
        username: '',
        password: ''
      },
      signUp: {
        username: '',
        email: '',
        // 新增身份选择
        identity: '',
        school: '',
        grade: '',
        subject: '',
        password: '',
        confirmPassword: ''
      },
      identities: [
        { value: '1',
          label: '教师'
        },
        { value: '0',
          label: '学生'
        }
      ],
      grades: [
        {
          label: '小学',
          code: 2,
          grades: 6
        },
        {
          label: '初中',
          code: 3,
          grades: 3
        },
        {
          label: '高中',
          code: 4,
          grades: 3
        }
      ],
      subjects: [],
      showsubject: false,
      numberZh: ['零', '一', '二', '三', '四', '五', '六'],
      signUpRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确的邮箱地址，否则将无法进行邮箱验证',
            trigger: 'blur'
          }
        ],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [{ validator: validatePassword2, trigger: 'blur' }],
        identity: [{ required: true, message: '请选择身份', trigger: 'blur' }],
        school: [{ required: true, message: '请填写学校', trigger: 'blur' }],
        grade: [{ required: true, message: '请选择年级', trigger: 'change' }],
        subject: [{ required: true, message: '请选择学科', trigger: 'change' }]
      },
      signInRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
          // { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }

    }
  },
  mounted() {
  },
  methods: {
    // 忘记密码函数，实现页面跳转
    retrievePWD() {
      if (this.signIn.username === '') {
        this.$notify({
          title: '跳转失败',
          message: '输入用户名再去重置密码吧',
          type: 'error'
        })
      } else {
        this.$router.push({
          path: '/retrievePassword',
          query: {
            username: this.signIn.username
          }
        })
      }
    },

    /* retrievePWD() {

      this.$router.push({ path: '/retrievePassword' })
    },*/

    // 解决注册页面浏览器默认填充el-input type=password的输入框问题
    changeType(e) {
      e.srcElement.type = 'password'
    },
    // 省市区数据选择
    seletekey(e, type) {
      if (e) {
        switch (type) {
          case 'province':
            Object.keys(this.provinces).filter(item => {
              if (this.provinces[item] === e) {
                // 选择省时 将区县重置为空
                this.$set(this.form, 'city', '')
                this.$set(this.form, 'area', '')
                this.citys = this.pcaaData[item]
              }
            })
            break
          case 'city':
            Object.keys(this.citys).filter(item => {
              if (this.citys[item] === e) {
                this.$set(this.form, 'area', '')
                this.areas = this.pcaaData[item]
              }
            })
            break
          case 'area':
            // console.log('第1条：' + Object.values(this.areas))
            // console.log('第2条：' + e)
            // console.log(this.areas)
            // 循环遍历areas里的值，当与所选值相同时，输出选中的值对应的键
            for (const key in Object.values(this.areas)) {
              if (e === Object.values(this.areas)[key]) {
                this.areaCodeQu = Object.keys(this.areas)[key]
                // console.log(this.areaCodeQu)
              }
            }
            break
        }
      }
    },
    // 获取学校数据
    async getSchoolInfo() {
      const { data: res } = await getSchoollist(this.areaCodeQu)
      this.school = []
      this.schoolInfo = res.data

      // 将重复的学校名字优化为学校+地址
      for (let i = 0; i < this.schoolInfo.length; i++) {
        for (let j = i + 1; j < this.schoolInfo.length; j++) {
          if (this.schoolInfo[i].name === this.schoolInfo[j].name) {
            this.schoolInfo[i].name = this.schoolInfo[i].name + '(' + this.schoolInfo[i].address + ')'
            this.schoolInfo[j].name = this.schoolInfo[j].name + '(' + this.schoolInfo[j].address + ')'
          }
        }
      }
    },
    // 获取学校选择框中的数据
    getChoosedSchoolName(e) {
      //console.log('getChoosedSchoolName(e)现在的选择:' + e)
      // 将现在的学校数据传给signUP注册需要的school值保存
      this.signUp.school = e
      // console.log('学校数据有无被记录:' + this.signUp.school)
    },
    // 获取学科数据
    async getSubject() {
      if(this.signUp.grade[0] === 2){
        this.selectedPeriod = "小学"
      } else if(this.signUp.grade[0] === 3){
        this.selectedPeriod = "初中"
      } else if(this.signUp.grade[0] === 4){
        this.selectedPeriod = "高中"
      }else{
        this.selectedPeriod = ""
      }
      getCatalogSubject(this.selectedPeriod).then(({ data }) => {
        this.subjects = data.data
      })
    },
    async getIdentity(){
      if(Number(this.signUp.identity) === 1){
        this.showsubject = true
      }else{
        this.showsubject = false
      }
    },
    toggle() {
      this.signUpActive = !this.signUpActive
    },
    async validateSignUp() {
      this.$refs.signUpForm.validate((valid) => {
        if (valid) {
          const signUp = this.signUp
          this.signUpLoading = true
          // console.log('signUp.identity' + signUp.identity)
          // console.log('Number(signUp.identity)' + Number(signUp.identity))
          register({
            username: signUp.username,
            email: signUp.email,
            school: signUp.school.name,
            password: signUp.password,
            userType: Number(signUp.identity),
            period: Number(signUp.grade[0]),
            grade: Number(signUp.grade[1]),
            subject: signUp.subject
          }).then((response) => {
            // console.log(response)
            this.signUpLoading = false
            if (response.data.code === 200) {
              this.$message.success(response.data.message)
              this.signIn.username = signUp.username
              this.signUpActive = false
              this.signUp.grade = ''
              this.signUp.subject = ''
              this.$refs.signUpForm.resetFields()
            } else {
              this.$message.warning(response.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    login() {
      const signIn = this.signIn
      for (const userInfo in signIn) {
        if (signIn[userInfo] === '') {
          this.$message.warning('请填写用户名和密码')
          return false
        }
      }
      login({
        username: signIn.username,
        password: signIn.password
      }).then((response) => {
        if (response.data.code === 200) {
          this.$message({
            message: response.data.message,
            type: 'success',
            duration: 1500
          })
          // authentication().then((response) => {
          //   const {
          //     data: { code }
          //   } = response
          //   // console.log(response)
          //   // console.log(code)
          // })

          this.$store.commit('login', response.data.data)
          const path = this.$route.query.redirect
          // 管理员登录（userType === 2）
          if (response.data.data.userType === 2) {
            this.$router.push('/admin')
          } else {
            // 普通登录（非管理员登录）
            this.$router.replace({
              path: path === '/' || path === undefined ? '/' : path
            })
          }
        } else {
          this.$message.warning(response.data.message)
        }
      })
    }
  }
}
</script>

<style scoped>
section {
  position: relative;
  min-height: 100vh;
  background: rgb(121 187 255);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

section .container {
  position: relative;
  width: 800px;
  height: 500px;
  background: #fff;
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

section .container .user {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
}

section .container .user .img-box {
  position: relative;
  width: 50%;
  height: 100%;
  background: #409eff;
  transition: 0.5s;
}

section .container .user .img-box img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

section .container .user .form-box {
  position: relative;
  width: 50%;
  height: 100%;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  transition: 0.5s;
  overflow: auto;
}

section .container .user .form-box form h2 {
  font-size: 18px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 2px;
  text-align: center;
  width: 100%;
  margin-top: 120px;
  margin-bottom: 10px;
  color: #555;
}
/* 滚动条样式设置 */
section .container .user .form-box::-webkit-scrollbar{
  /* display: none; */
  /* //滚动条宽高 */
  width: 5px;
  height: 10px;
}
section .container .user .form-box::-webkit-scrollbar-thumb{
  /* //滚动条颜色和圆角 */
  background-color: #dbd9d9;
  border-radius: 3px;
}
.form {
  width: 100%;
}

.form .el-form-item {
  margin-bottom: 0;
}

.form >>> .el-form-item__error {
  margin-top: -10px;
}

section .container .user .form-box >>> input {
  position: relative;
  width: 100%;
  padding: 10px;
  background: #f5f5f5;
  color: #333;
  border: none;
  outline: none;
  box-shadow: none;
  margin: 8px 0;
  font-size: 14px;
  letter-spacing: 1px;
  border-radius: 0;
}

.submit-btn {
  margin: 8px 0;
  padding: 10px 30px;
  border-radius: 0;
  letter-spacing: 1px;
  transition: 0.3s;
}

section .container .user .form-box form .signup {
  position: relative;
  margin-top: 20px;
  font-size: 12px;
  letter-spacing: 1px;
  color: #555;
  text-transform: uppercase;
  font-weight: 300;
}

section .container .user .form-box form .signup span {
  font-weight: 600;
  cursor: pointer;
  text-decoration: none;
  color: #409eff;
}

section .container .sign-up-box {
  pointer-events: none;
}

section .container.active .sign-up-box {
  pointer-events: initial;
}

section .container .sign-up-box .form-box {
  left: 100%;
}

section .container.active .sign-up-box .form-box {
  left: 0;
}

section .container .sign-up-box .img-box {
  left: -100%;
}

section .container.active .sign-up-box .img-box {
  left: 0;
}

section .container .sign-in-box .form-box {
  left: 0;
}

section .container.active .sign-in-box .form-box {
  left: 100%;
}

section .container .sign-in-box .img-box {
  left: 0;
}

section .container.active .sign-in-box .img-box {
  left: 100%;
}

.ShengShiQu{
  display: flex;
}

@media (max-width: 991px) {
  section .container {
    max-width: 400px;
  }
  section .container .img-box {
    display: none;
  }
  section .container .user .form-box {
    width: 100%;
  }
}
</style>
